<template>
	<view class="page flex-col">
		<view class="group_1 flex-col">
			<view class="group_2 flex-col">
				<view class="box_2 flex-row">
					<view class="text-group_1 flex-col">
						<text class="text_3">Hi，欢迎！</text>
						<text class="text_4">未注册的手机号将自动创建为账号</text>
					</view>
				</view>
			</view>
			<view class="group_3 flex-col">
				<view class="">
					<view :class="isClickIndex===0?'':'text-wrapper_L flex-col'" @click="userLogin">
						<text class="text_5">账号密码登录</text>
					</view>
					<view style="float: right;margin-right: 50rpx;" :class="isClickIndex===1?'':'text-wrapper_2 flex-col'" @click='noLock'>
						<text style="font-weight: 700;" class="text_9">账号注册</text>
					</view>
				</view>
				<view class="isClickIndex">
				  <view class="" v-if="isClickIndex === 0">
					<view class="group_4 flex-col"></view>
					<view class="input_1 flex-row" style="height: 90rpx;display: flex;align-items: center;">
						<view class="" style="display: flex;margin-top: -10rpx;">
							<image class="icon_1 shrink-0" referrerpolicy="no-referrer"
								src="../../static/image/user.png" />
							<input class="text_6" style="padding-left: 20rpx;" type="text" placeholder="请输入手机号"
								v-model="phone" />
						</view>
					</view>
					<view class="group_5 flex-row" style="">
						<view class="image-text_1 flex-row">
							<image class="icon_2 shrink-0" referrerpolicy="no-referrer"
								src="../../static/image/lock.png" />
							<input class="text-group_2" style="padding-left: 20rpx;" type="password" placeholder="密码"
								v-model="password" />
						</view>
					</view>
					<view class="group_6 flex-row justify-between">
						<view class="image-text_2 flex-row justify-between">
							<uni-data-checkbox selectedColor="#275515" selectedTextColor="#275515" :multiple="true"
								v-model="isRemember" :localdata="range" @change="handleRememberPwd"></uni-data-checkbox>
						</view>
						<view class="text_7">
							<navigator url="/pages/login/forget">
								找回密码
							</navigator>
						</view>
					</view>
					<button class="button_1 flex-col" @click="login" style="margin-top: 50rpx;">
						<text class="text_8">登录</text>
					</button>
				</view>

				
				<view style="text-align: center;padding-top: 20rpx;"   v-else>
					    <view class="group_4" style="margin-left:400rpx ;margin-top: -10rpx;"></view>
									<view class="input_1 flex-row" style="height: 90rpx;display: flex;align-items: center;">
										<view class="" style="display: flex;margin-top: -10rpx;">
											<image class="icon_1 shrink-0" referrerpolicy="no-referrer"
												src="../../static/image/user.png" />
											<input class="text_6" style="padding-left: 20rpx;" type="text" placeholder="请输入手机号"
												v-model="phone2" />
										</view>
									</view>
									
									<view class="" style="display: flex;justify-content: space-between;">										
										<view class="group_5 flex-row" style="width: 320rpx;">
											<view class="image-text_1 flex-row" style="width:200rpx;">
												<image class="icon_2 shrink-0" referrerpolicy="no-referrer"
													src="../../static/image/lock.png" />
												<input class="text-group_2" style="padding-left: 20rpx;"  placeholder="请输入验证码"
												 v-model="yzcode" />						
											</view>
										</view>
										<view @click='getYZM' class="" style="width: 190rpx;height: 88rpx;font-size: 14px;margin-top: 22rpx;border: 2px solid #eaeaea;border-radius: 10rpx;display: flex;justify-content: center;align-items: center;">
											{{codeTxt}}
										</view>
									</view>
									
									<view class="group_5 flex-row" style="">
										<view class="image-text_1 flex-row">
											<image class="icon_2" 
												src="../../static/image/lock.png" />
											<input class="text-group_2" style="padding-left: 20rpx;" type="password" placeholder="密码"
												v-model="password2" />
										</view>
									</view>
			
									<button class="button_11 flex-col" @click='mianmiLogin'>
										<text class="text_88">注册</text>
									</button>					
				</view>
				
				</view>
								
			</view>
            
			<view class="group_7 flex-col" style="margin-top: -200rpx;">
				<view style="align-items: center;" class="image-text_3 flex-row justify-between">
					<label class="radio">
						<radio value="" />
					</label>
					<view class="text-group_4">
						<text class="text_11">我已阅读并同意</text>
						<text class="text_12">《用户协议》</text>
						<text class="text_13">和</text>
						<text class="text_14">《隐私政策》</text>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>
<script>
	import {
		loginApi,
		newLoginApi,
		getyzcodeApi,
		phonecodeApi
	} from "@/api/api.js"
	export default {
		data() {
			return {
				range: [{
					"value": 1,
					"text": "记住密码"
				}],
				constants: {},
				isClickIndex: 0,
				// :multiple="true" 时（多选） ， value/v-model 的值是 Array 类型
				isRemember: uni.getStorageSync('isRemember') ? [1] : [], //默认未选
				phone: '',
				phone2:'',
				password: '',
				password2:'',
				userPhone: "",
				yzcode:'',
				codeTxt: "获取验证码",
				time: 60000,
				timer: null,
				
			};
		},
		onLoad() {
			if (uni.getStorageSync('isRemember') && uni.getStorageSync('loginform')) {
				this.phone = uni.getStorageSync('loginform').phone
				this.password = uni.getStorageSync('loginform').pwd
			}
		},
		watch: {
			isClickIndex(val) {
				console.log(val, 'val')
			}
		},
		methods: {
			handleRememberPwd(e) {
				// e.detail.value.length有值表示勾选
				console.log(e, '2222222');
				if (e.detail.value.length) {
					uni.setStorageSync('isRemember', true)

					this.isRemember = e.detail.value
					return
				}
				this.isRemember = []
				uni.setStorageSync('isRemember', false)
			},
			
			/* 获取验证码 */

			getYZM() {
				const phoneToUse = this.phone2;
				console.log(phoneToUse,'本地保存的手机号')
			  if (!this.phone2) {
			    uni.showToast({
			      title: '请输入正确手机号',
			      icon: "none"
			    });
			    return;
			  } 
			
			  getyzcodeApi({
			    phone: this.phone2,
			    event: 'register'
			  }).then(res => {
			    console.log(res);
			    this.timer = setInterval(() => {
			      this.time = this.time - 1000; // 时间间隔改成1秒
			      this.codeTxt = Math.floor(this.time / 1000) + "s后重试"; // 计算时间间隔也改成1秒
			      if (this.time <= 0) { // 注意此处使用 <= 0 判断
			        clearInterval(this.timer);
			        this.time = 60000;
			        this.codeTxt = "获取验证码";
			      }
			    }, 1000); // 时间间隔改成1秒
			  });
			},
			/* 网页验证码登录    注册*/
            mianmiLogin(){
				const params={
					phone:this.phone2,
					code:this.yzcode,
					password:this.password2
				}
				phonecodeApi(params).then(res=>{
					console.log(res,'注册成功')
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}).catch(e => {
				})
			},
			// 登录
			login() {
				const that = this
				loginApi({
					phone: this.phone,
					password: this.password
				}).then(res => {
					console.log('login success', res.data.data.token);
					// 将 token 存储到本地
					uni.setStorageSync('token', res.data.data.token);
					//缓存账号密码
					uni.setStorageSync('loginform', {
						phone: that.phone,
						pwd: that.password
					});

					// 跳转到首页
					uni.switchTab({
						url: '/pages/tabbar/home'
					});
				}).catch(e => {
					console.log('login fail', e);
				})
			},
			loginFast(key) {
				console.log(key, "!!!!!!!!!!!")
				newLoginApi({
					phone: key
				}).then(res => {
					// 将 token 存储到本地
					uni.setStorageSync('token', res.data.data.token);
					console.log('login success', res.data.data.token);
					// 跳转到首页
					uni.switchTab({
						url: '/pages/tabbar/home'
					});
				})
			},
			/* 本地号码一键登录*/
			oneClickLogin() {
				console.log("手机号一键登录")
				var this_ = this
				// 预登陆
				uni.preLogin({
					provider: "univerify",
					success: () => {
						uni.login({
							provider: "univerify",
							univerifyStyle: {
								"icon": {
									"path": "static/image/logo.png", // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
								},
								"otherLoginButton": {
									"visible": false, // 是否显示其他登录按钮，默认值：true
								},
								"authButton": {
									"normalColor": "#275515", // 授权按钮正常状态背景颜色 默认值：#3479f5
									"highlightColor": "#275515", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
									"disabledColor": "#33701b", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
								},
							},
							success: (res) => {
								console.log("一键登录调用返回的数据", res)
								uniCloud.callFunction({
									name: "login", // 云函数名称
									data: {
										access_token: res.authResult
											.access_token, // 客户端一键登录接口返回的access_token
										openid: res.authResult.openid // 客户端一键登录接口返回的openid
									}
								}).then((dataRes) => {
									console.log("云函数返回的参数", dataRes)
									let phone = dataRes.result.data.phoneNumber
									this.userPhone = dataRes.result.data.phoneNumber
									// 这里进行登录操作
									this.loginFast(phone)
									uni.closeAuthView()
								}).catch((err) => {
									console.log("云函数报错", err)
									uni.showToast({
										title: err.errMsg,
										icon: "none"
									})
									this_ = this
									setTimeout(() => {
										uni.closeAuthView() //关闭一键登录弹出窗口
									}, 500)
								})
								uni.showToast({
									title: res.authResult,
									icon: "none"
								})
								// console.log("云函数调用返回数据", dataRes)
							},
							fail(err) {
								// 登录失败或者点击其他登录方式,自定义按钮等
								console.log("一键登录uni.login失败", err)
								uni.showToast({
									title: res.errMsg || err.metadata?.resultDesc,
									icon: "none"
								})
								setTimeout(() => {
									uni.closeAuthView() //关闭一键登录弹出窗口
									this_.onClickMsgLogin()
								}, 500)
							}
						})
					},
					fail(res) {
						console.log("一键登录uni.preLogin失败", res)
						if (res.errMsg != "login:ok") {
							// 这里注意有个小坑: 不同运营商,返回的报错字段不同, 经过测试, 以下几乎包含了三大运营商报错字段
							uni.showToast({
								title: res.errMsg || res.metadata.resultMsg || res.metadata.error_data ||
									res.metadata.resultDesc || "请检查是否插入有效sim卡及开启蜂窝数据网络",
								icon: "none"
							})
						}
						//如果手机没有插入有效的sim卡，或者手机蜂窝数据网络关闭，
						//都有可能造成预登录校验失败。

						setTimeout(() => {
							// 预登陆失败, 做其他操作
							this_.onClickMsgLogin()
						}, 500)
					}
				})
			},
			userLogin() {
				// console.log('账号')
				this.isClickIndex = 0
			},

			noLock() {
              // #ifdef APP-PLUS
                 this.oneClickLogin();
                 // #endif            
                 // #ifdef H5
                 this.isClickIndex = 1 - this.isClickIndex; // 切换值，0 变为 1，1 变为 0
                 // #endif
			}
		},
	};
</script>
<style lang="scss" scoped>
	@import '../../static/style/common.scss';
	@import '../../static/style/login/index.scss';

	/deep/ .uni-radio-input.uni-radio-input-checked {
		background-color: rgba(39, 85, 21, 1) !important;
		border-color: rgb(39, 85, 21) !important;

	}

	/deep/ .uni-radio-input {
		width: 28rpx !important;
		height: 28rpx !important;
	}

	/* .whitebg {
		background: url(https://lanhu.oss-cn-beijing.aliyuncs.com/SketchPng95594550c1b6c411d3fd675731709ab895d5cc2f41d08ed949e3afd2db1c1abd) -6rpx 0rpx no-repeat;
		background-size: 666rpx 654rpx;
	} */

	.group_4r {
		position: absolute;
		background-color: rgba(39, 85, 21, 1);
		border-radius: 2px;
		width: 19px;
		height: 4px;
		top: 68rpx;
		right: 104rpx;
	}


	.text_77 {
		overflow-wrap: break-word;
		color: rgba(51, 51, 51, 1);
		font-size: 56rpx;
		font-family: DINAlternate-Bold;
		font-weight: 700;
		white-space: nowrap;
		line-height: 64rpx;
		display: flex;
		justify-content: center;
		margin-top: 100rpx;
	}

	.button_11 {
		background-color: rgba(39, 85, 21, 1);
		border-radius: 24px;
		margin: 96rpx 0 20rpx 0rpx;
		padding: 22rpx 150rpx 22rpx 148rpx;

		.text_88 {
			overflow-wrap: break-word;
			color: rgba(255, 255, 255, 1);
			font-size: 28rpx;
			font-family: PingFangSC-Medium;
			font-weight: 500;
			text-align: center;
			white-space: nowrap;
			line-height: 40rpx;
		}
	}

	.text_99 {
		overflow-wrap: break-word;
		color: rgba(39, 85, 21, 1);
		font-size: 28rpx;
		font-weight: NaN;
		text-align: center;
		white-space: nowrap;
		line-height: 40rpx;
		display: flex;
		justify-content: center;
		margin-top: 40rpx;
	}


	/* /deep/ .uni-radio-input.uni-radio-input-checked::before{
	display: none!important;
} */
	.image-text_2 {
		width: auto !important;
	}
</style>